package com.dailyblue.java.cloud.sentinel.consumer.handler;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSONArray;
import com.dailyblue.java.commons.util.JsonResult;
import com.dailyblue.java.commons.util.ResultTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
@Slf4j
public class MyExceptionHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        log.info("异常类型是：{}", e.getClass());
        log.info("异常：{}", e.getRuleLimitApp());
        JsonResult result = ResultTool.fail("出现了错误，" + e.getMessage());
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.println(JSONArray.toJSONString(result));
    }
}
